/**
 * Copyright(c) KuGou-Inc.All Rights Reserved. 
 */
package top.suven.base.util.utilize;

import top.suven.base.util.PropertiesHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <pre>
 * 程序的中文名称。
 * </pre>
 * @author suven  pf_qq@163.com
 * @version 1.00.00
 * <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容: 
 * </pre>
 */
public class TestUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
	
	/**
	 * 根据环境变量设置值。
	 * @param remoteAddr
	 * @return
	 */
	public static String getRmtJenkins(String remoteAddr){
		Class<?> callerCls;
		try {
			callerCls = getCaller();
		} catch (ClassNotFoundException e) {
			logger.error("", e);
			return remoteAddr;
		}
		String absPath = "";
		if(callerCls!=null)
			absPath = callerCls.getResource("").getFile();
		String tail = "";
		logger.warn("Current sub project absolute path is {}", absPath);
		if (absPath.indexOf("show-focus") != -1)
			tail = "/focus";
		else if (absPath.indexOf("show-rank") != -1)
			tail = "/rank";
		else if (absPath.indexOf("show-web") != -1)
			tail = "/web";
		else if (absPath.indexOf("show-admin") != -1)
			tail = "/admin";
		else if (absPath.indexOf("show-upload") != -1)
			tail = "/upload";
			
		logger.warn("Current sub project tail is {}", tail);	
			
		if(isJenkinsJunit()){
			String junitUrl =  getJenkinsJunitIp(getJenkinsJunitConf());
			if(StringUtils.isNotEmpty(junitUrl))
				return junitUrl+tail;
		}
		return remoteAddr;
	}

	public static boolean isJenkinsJunit(){
        return StringUtils.isNotEmpty(getJenkinsJunitConf()) && StringUtils.isNotEmpty(getJenkinsJunitIp(getJenkinsJunitConf()));
    }
	
	public static Class<?>  getCaller() throws ClassNotFoundException{   
        StackTraceElement stack[] = Thread.currentThread().getStackTrace();  
        for (StackTraceElement ste:stack){   
         if((ste.getClassName().indexOf("MvcTestUtil"))!=-1 || (ste.getClassName().indexOf("JsonTestUtil"))!=-1) {
             return Class.forName(ste.getClassName());
         }
        }  
        return null;
      }  
	
	public static String getJenkinsJunitConf(){
		return System.getenv("JENKINS_JUNIT");
	}
	
	private static String getJenkinsJunitIp(String conf) {
		String[] ips = conf.split(","); 
		for(String ip:ips){
			if(ip.startsWith(PropertiesHelper.getProp("project")))
				return ip.split("@")[1];
		}
		return null;
	}
}
